const resultsTable = document.getElementById("results-table");
const errorText = document.createElement("p");
errorText.className = "error";

document.querySelector("form").addEventListener("submit", async (event) => {
  event.preventDefault();

  errorText.remove();

  const ipAddress = document.getElementById("ip-address").value;
  if (!ipAddress) {
    errorText.textContent = "Please enter an IP address or hostname.";
    document.querySelector("form").append(errorText);
    return;
  }

  try {
    const response = await axios.post("/scan", { ipAddress });
    const data = response.data;

    if (!data || !Array.isArray(data) || data.length === 0) {
      throw new Error("No results found.");
    }

    while (resultsTable.lastChild) {
      resultsTable.removeChild(resultsTable.lastChild);
    }

    const headers = ["Port", "Protocol", "Service"];
    const headerRow = document.createElement("tr");
    for (const header of headers) {
      const th = document.createElement("th");
      th.textContent = header;
      headerRow.appendChild(th);
    }
    resultsTable.appendChild(headerRow);

    for (const result of data) {
      const row = document.createElement("tr");
      const port = document.createElement("td");
      const protocol = document.createElement("td");
      const service = document.createElement("td");
      port.textContent = result.port;
      protocol.textContent = result.protocol;
      service.textContent = result.service;
      row.appendChild(port);
      row.appendChild(protocol);
      row.appendChild(service);
      resultsTable.appendChild(row);
    }

    resultsTable.classList.remove("fadeOut");
    resultsTable.classList.add("fadeIn");
  } catch (error) {
    console.error(error);
    errorText.textContent = error.message;
    document.querySelector("form").append(errorText);
  }
});
